package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);
        //如果添加到数据库中执行成功，就执行添加到redis
        if (success){
            //2.添加任务到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId        任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {

        boolean flag = false;

        //删除任务，更新日志
        Task task = updateDb(taskId,ScheduleConstants.EXECUTED);

        //删除redis的数据
        if(task != null){
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级拉取任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key =type + "_" + priority;
        Task task = null;
        //从redis中拉取数据 pop
        String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotBlank(taskJson)){
            //转为Task类型的对象
            task = JSON.parseObject(taskJson, Task.class);
            //修改数据库信息
            //调用删除数据库方法和更新 传入taskId和状态码1
            updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
        }

        return task;
    }

    /**
     * 删除redis中的任务数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("task cancel exception taskid={}",taskId);
        }

        return task;
    }

    /**
     * 添加到redis中
     * @param task
     */
    private void addTaskToCache(Task task) {
        //1.获取当前时间和未来五分钟时间
        long currentTimeMillis = System.currentTimeMillis();//当前时间
        Calendar calendar = Calendar.getInstance();//初始化一个日历对象
        calendar.add(Calendar.MINUTE,5);//在当前时间添加5分钟
        long timeInMillis = calendar.getTimeInMillis();//未来五分钟的时间
        //获得key 类型+优先级
        String key = task.getTaskType() + "_" + task.getPriority();
        //2.判断任务执行的时间，如果小于等于当前时间则立即添加到list，如果是未来五分钟内执行的添加到zset 其他数据补不处理
        if (task.getExecuteTime() <= currentTimeMillis){
            //添加到List
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime() <= timeInMillis){
            //添加到zset
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        //保存任务表
        Taskinfo taskinfo = new Taskinfo();
        //复制task到taskinfo中
        BeanUtils.copyProperties(task,taskinfo);
        //设置执行时间
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        int count = taskinfoMapper.insert(taskinfo);
        //设置taskId
        task.setTaskId(taskinfo.getTaskId());

        //保存任务到日志数据
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        //复制数据到日志对象
        BeanUtils.copyProperties(taskinfo,taskinfoLogs);
        //设置版本为1 乐观锁
        taskinfoLogs.setVersion(1);
        //设置状态为 //已执行状态
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
        //
        int count1 = taskinfoLogsMapper.insert(taskinfoLogs);

        return count== 1 && count1 == 1;
    }

    /**
     * 未来数据定时刷新 每分钟刷新一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        String token = cacheService.tryLock("FUTURE_TASK_SYNC",1000*30);
        if (StringUtils.isNotBlank(token)){

            log.info("未来数据定时刷新---定时任务");
            //获取所有未来数据的集合Key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {//future_100_50
                //在zset里面查找 到了当前时间就同步到list中
                //按照key和分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                //获取当前数据的key  topic                     //截取,通过futurekey截取为两部分,前半部分为future,后面部分为通用的key.
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //同步数据
                if (!tasks.isEmpty()){
                    //通过管道进行刷新数据
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    log.info("成功的将"+ futureKey + "刷新到了" + topicKey);
                }
            }
        }
    }

    /**
     * 数据库任务同步到redis中
     */
    @PostConstruct //预加载,服务一启动就预加载初始化对象
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadDate(){
        //1.清理缓存
        clearCache();
        //2.查询符合条件的任务, 小于未来五分钟的数据
        Calendar calendar = Calendar.getInstance();//初始化一个日历对象
        calendar.add(Calendar.MINUTE,5);//在当前时间添加5分钟
        //查询小于未来五分钟的所有数据
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        //判断是否为空
        if (taskinfoList !=null && taskinfoList.size() >0){
            //循环遍历得到每一个taskinfo
            for (Taskinfo taskinfo : taskinfoList) {
                //3.把任务添加到redis
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                //要对ExecuteTime重新复制
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
        log.info("数据库的任务同步到了redis");
    }

    /**
     * 清理缓存
     */
    private void clearCache() {
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topickeys);
        cacheService.delete(futureKeys);
    }
}

